package com.gavindon.android.view.combo

import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.text.HtmlCompat
import androidx.leanback.widget.VerticalGridView
import com.gavindon.android.R
import com.gavindon.android.adapters.ComboContentAdapter
import com.gavindon.android.adapters.ComboLeftAdapter
import com.gavindon.android.base.*
import com.gavindon.android.entity.ComboResp
import com.gavindon.android.entity.CourseOutputDTO
import com.gavindon.android.network.DataResult
import com.gavindon.android.utils.GoodsType
import com.gavindon.android.utils.toFullVideoOrDetailPage
import com.gavindon.android.utils.ymd
import com.gavindon.android.view.video.IntroMoreDialog
import com.gavindon.android.view.video.VideoDetailActivity
import com.gavindon.android.viewmodel.ComboViewModel
import com.gavindon.android.viewmodel.CommonViewModel
import org.jetbrains.anko.*

/**
 * description: 套餐信息
 * Created by liNan on  2022-3-2 22:52
 */
class ComboLstActivity : BaseActivity() {
    override val layoutId = R.layout.activity_combo_lst
    private lateinit var leftRv: VerticalGridView
    private lateinit var contentRv: VerticalGridView
    private lateinit var mViewModel: ComboViewModel
    private lateinit var mCommonViewModel: CommonViewModel

    private lateinit var buyBtn: FrameLayout
    private lateinit var tvOriginalPrice: TextView
    private lateinit var tvComboDetail: TextView
    private lateinit var tvNowPrice: TextView
    private lateinit var tvComboExpired: TextView
    private lateinit var ivIntroMore: ImageView

    //如果是packageId则是查看套餐详情
    private var packageId = ""

    //如果是课程id展示所有套餐
    private var courseId = ""


    private val mLeftAdapter: ComboLeftAdapter =
        ComboLeftAdapter(R.layout.adapter_education_left, null)

    private val mContentAdapter: ComboContentAdapter =
        ComboContentAdapter(R.layout.adapter_combo_content, null)

    //套餐信息

    override fun onInit(savedInstanceState: Bundle?) {
        mViewModel = getViewModel()
        mCommonViewModel = getViewModel()
        leftRv = findViewById(R.id.rvLeft)
        contentRv = findViewById(R.id.rv_content)
        tvComboDetail = findViewById(R.id.tv_detail)
        packageId = intent.getStringExtra(INTENT_PACKAGE_ID) ?: ""
        courseId = intent.getStringExtra(INTENT_COURSE_ID) ?: ""
        buyBtn = findViewById(R.id.btn_buy)
        tvOriginalPrice = findViewById(R.id.tv_orign_price)
        tvNowPrice = findViewById(R.id.tv_now_price)
        tvComboExpired = findViewById(R.id.tv_expired_time)
        ivIntroMore = findViewById(R.id.intro_more)
        initSingleLeft()
        //购买按钮只进行购买套餐
        buyBtn.setOnClickListener {
            checkPayResult(packageId, GoodsType.COMBO.ordinal.toString())
            setCheckListener {
                if (!it) {
                    startActivityForResult<BuyActivity>(
                        BUY_REQUEST_CODE, Pair(INTENT_GOODS_TYPE, GoodsType.COMBO.ordinal),
                        Pair(INTENT_COMBO_ID, packageId)
                    )
                } else {
                    toast("该套餐您已购买")
                }
            }
        }
        buyBtn.setOnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    ivIntroMore.requestFocus()
                    return@setOnKeyListener true
                }
            }
            return@setOnKeyListener false
        }
        ivIntroMore.setOnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    contentRv.requestFocus()
                    return@setOnKeyListener true
                }
            }
            return@setOnKeyListener false
        }
    }

    private fun setIntroduce(detail: String) {
        val introduce =
            HtmlCompat.fromHtml(detail, HtmlCompat.FROM_HTML_MODE_COMPACT)
        val html = "介绍:${introduce}"
        val spannable = SpannableString(html)
        val absoluteSizeSpan = AbsoluteSizeSpan(sp(18))
        val textColorSpan = ForegroundColorSpan(Color.parseColor("#b3ffffff"))
        val textColorSpan2 = ForegroundColorSpan(Color.parseColor("#80ffffff"))
        val absoluteSizeSpan2 = AbsoluteSizeSpan(sp(16))
        spannable.setSpan(absoluteSizeSpan, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        spannable.setSpan(textColorSpan, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        spannable.setSpan(absoluteSizeSpan2, 3, html.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        spannable.setSpan(textColorSpan2, 3, html.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        tvComboDetail.text = spannable
        ivIntroMore.setOnClickListener {
            val dialog = IntroMoreDialog(introduce.toString())
            dialog.show(supportFragmentManager, "introduce")
        }
    }

    /**
     * 单个套餐
     */
    private fun initSingleLeft() {
        leftRv.setNumColumns(1)
        leftRv.adapter = mLeftAdapter
/*        if (packageId.isNotEmpty()) {
            //根据套餐id获取套餐信息
            mViewModel.getCombLstById(packageId).observe(this) {
                if (it is DataResult.Success) {
                    mLeftAdapter.setList(
                        listOf(
                            ComboResp(packageId = packageId, packageName = it.data.packageName)
                        )
                    )
                    it.data.originalPrice?.let { p ->
                        tvOriginalPrice.text = "￥$p"
                    }
                    it.data.presentPrice?.let { p ->
                        tvNowPrice.text = "￥$p"
                    }
                    tvOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    tvComboExpired.text =
                        "${it.data.serviceLife}${it.data.serviceLifeCompany?.ymd()}"
                    it.data.courseOutputDTOList?.let { it1 -> initContent(it1) }
                    setIntroduce(it.data.details.toString())
                    it.data.courseOutputDTOList?.let { it1 -> initContent(it1) }
                }
            }
        } else {
            mCommonViewModel.queryCombLst(courseId).observe(this) {
                if (it is DataResult.Success) {
                    mLeftAdapter.setList(it.data)
                }
            }
            mLeftAdapter.setFocusListener {
                reqContent(it)
            }
        }*/

        //当套餐id和课程id同时存在时说明左侧列表需要展示多个套餐并且选中到某个套餐上
        if (packageId.isNotEmpty() && courseId.isNotEmpty()) {
            mCommonViewModel.queryCombLst(courseId).observe(this) {
                if (it is DataResult.Success) {
                    //如果点击套餐则滚动到当前点击的套餐上。
                    val currentPackage = it.data.find { item -> item.packageId == packageId }
                    val index = it.data.indexOf(currentPackage)
                    if (index != -1) {
                        leftRv.layoutManager?.scrollToPosition(index)
                    }
                    mLeftAdapter.setList(it.data)
                    mLeftAdapter.setFocusListener { comboResp ->
                        reqContent(comboResp.packageId ?: "")
                    }
                }
            }
        } else if (packageId.isNotEmpty()) {
            //根据套餐id获取套餐信息
            mViewModel.getCombLstById(packageId).observe(this) {
                if (it is DataResult.Success) {
                    mLeftAdapter.setList(
                        listOf(
                            ComboResp(
                                packageId = packageId,
                                packageName = it.data.packageName,
                                validity = it.data.validity
                            )
                        )
                    )
                    it.data.originalPrice?.let { p ->
                        tvOriginalPrice.text = "￥$p"
                    }
                    it.data.presentPrice?.let { p ->
                        tvNowPrice.text = "￥$p"
                    }
                    tvOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    tvComboExpired.text =
                        if (it.data.serviceLife != null && it.data.serviceLife == 0)
                            "永久有效" else "${it.data.serviceLife}${it.data.serviceLifeCompany?.ymd()}"
                    it.data.courseOutputDTOList?.let { it1 -> initContent(it1) }
                    setIntroduce(it.data.details.toString())
                    it.data.courseOutputDTOList?.let { it1 -> initContent(it1) }
                }
            }
        } else if (courseId.isNotEmpty()) {
            mCommonViewModel.queryCombLst(courseId).observe(this) {
                if (it is DataResult.Success) {
                    mLeftAdapter.setList(it.data)
                    mLeftAdapter.setFocusListener { comboResp ->
                        reqContent(comboResp.packageId!!)
                    }
                }
            }

        }

    }

    /**
     * 根据套餐id获取课程数据
     */
    private fun reqContent(packageId: String) {
        this.packageId = packageId
        mViewModel.getCombLstById(packageId).observe(this) {
            if (it is DataResult.Success) {
                it.data.originalPrice?.let { p ->
                    tvOriginalPrice.text = "￥$p"
                }
                it.data.presentPrice?.let { p ->
                    tvNowPrice.text = "￥$p"
                }
                tvOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                tvComboExpired.text =
                    if (it.data.serviceLife != null && it.data.serviceLife == 0)
                        "永久有效" else "${it.data.serviceLife}${it.data.serviceLifeCompany?.ymd()}"
//                tvComboExpired.text = "${it.data.serviceLife}${it.data.serviceLifeCompany?.ymd()}"
                it.data.courseOutputDTOList?.let { it1 -> initContent(it1) }
                setIntroduce(it.data.details.toString())
            }
        }
    }

    private fun initContent(courseOutputDTOList: List<CourseOutputDTO>) {
        contentRv.setNumColumns(4)
        contentRv.setItemSpacing(dip(30))
        contentRv.adapter = mContentAdapter
        if (!courseOutputDTOList.isNullOrEmpty()) {
            mContentAdapter.setList(courseOutputDTOList)
            mContentAdapter.setOnItemClickListener { adapter, view, positon ->
                val itemData = adapter.getItem(positon) as CourseOutputDTO
                checkPayResult(itemData.courseId, GoodsType.LESSON.ordinal.toString())
                setCheckListener {
                    if (!it) {
                        startActivityForResult<BuyActivity>(
                            BUY_REQUEST_CODE, Pair(INTENT_GOODS_TYPE, GoodsType.LESSON.ordinal),
                            Pair(INTENT_COMBO_ID, itemData.courseId)
                        )
                    } else {
                        //如果已经支付跳转视频界面
                        this.toFullVideoOrDetailPage(
                            itemData.subjectType,
                            itemData.courseId,
                            itemData.courseName
                        )
                    }
                }
            }
            mContentAdapter.setUpListener {
//                buyBtn.requestFocus()
                ivIntroMore.requestFocus()
            }
        }

    }

    private fun checkPayResult(id: String, orderType: String) {
        mViewModel.checkIsCanLook(orderType, id).observe(this) {
            if (it is DataResult.Success) {
                if (!it.data.isNullOrEmpty()) {
                    when (it.data[0].validity) {
                        0 -> canLookListener?.invoke(false)
                        1 -> {
//                            toast("购买已过期")
                            canLookListener?.invoke(false)
                        }
                        2 -> {
//                            toast("您已购买，可返回观看")
                            canLookListener?.invoke(true)
                        }
                    }
                } else {
                    canLookListener?.invoke(false)
                }

            } else {
                canLookListener?.invoke(false)
            }
        }
    }

    private var canLookListener: ((Boolean) -> Unit)? = null
    fun setCheckListener(listener: (Boolean) -> Unit) {
        this.canLookListener = listener
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (requestCode == BUY_REQUEST_CODE) {
            val id = data?.getStringExtra("id")
            val orderType = data?.getIntExtra("orderType", -1).toString()
            if (!id.isNullOrEmpty() && orderType != "-1") {
                checkPayResult(id, orderType)
            }

        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}